package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.config.AlipayConfig;
import com.chixing.pojo.Car;
import com.chixing.pojo.Flow;
import com.chixing.pojo.Myorder;
import com.chixing.service.CarService;
import com.chixing.service.CouponService;
import com.chixing.service.FlowService;
import com.chixing.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@Component
public class PayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CarService carService;
    @Autowired
    private FlowService flowService;

    @Autowired
    private CouponService couponService;

    @PostMapping("alipay")
    @ResponseBody
    public String alipay(Integer orderId,Integer carId){
        System.out.println ("============进入alipay===================================");
        System.out.println ();
        Myorder myorder = orderService.getById (orderId);
        System.out.println ("myorder中的数据============="+myorder);
        Car car = carService.getById (carId);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient (AlipayConfig.gatewayUrl,AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,"json",AlipayConfig.charset,
                AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 支付宝支付完成后，走哪个url : 同步、异步
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        Integer out_trade_no = orderId;
        Float total_amount = myorder.getMyorderTotalPrice ();
        String subject = car.getCarName ();
        String body = "用户购买的商品"+car.getCarName ();
        String timeout_express = "1c";

        System.out.println("out_trade_no:"+out_trade_no);
        System.out.println("total_amount:"+total_amount);
        System.out.println("subject:"+subject);
        System.out.println("body:"+body);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //发送请求
        //获得支付宝返回数据
        String result =null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();  // 执行支付  --- 支付宝 执行支付，有支付页面
            System.out.println("支付成后，支付宝返回的数据是："+ result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return result;

    }


    // 支付完成后，我们要如何处理 结果 数据？
    // 调用支付 是同步请求， 该方法就是 同步处理的
    @GetMapping("/alipayReturnNotice")
    @ResponseBody
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        System.out.println ("支付成功后，支付宝返回的所有的数据：" + request);
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String> ();
        Map<String, String[]> requestParams = request.getParameterMap ();
        for (Iterator<String> iter = requestParams.keySet ().iterator (); iter.hasNext (); ) {
            String name = (String) iter.next ();
            System.out.println ("return notice name:" + name);
            String[] values = (String[]) requestParams.get (name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String (valueStr.getBytes ("ISO-8859-1"), "utf-8");
            params.put (name, valueStr);
        }
        System.out.println ("params:" + params);

        boolean signVerified = AlipaySignature.rsaCheckV1 (params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        System.out.println ("return notice signVerified:" + signVerified);
        ModelAndView mav = new ModelAndView ();
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String (request.getParameter ("out_trade_no").getBytes ("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String (request.getParameter ("trade_no").getBytes ("ISO-8859-1"), "UTF-8");
            //付款金额
            String total_amount = new String (request.getParameter ("total_amount").getBytes ("ISO-8859-1"), "UTF-8");

            System.out.println ("return out_trade_no:" + out_trade_no);//订单编号
            System.out.println ("return trade_no:" + trade_no);//流水号
            System.out.println ("return total_amount:" + total_amount);//流水金额

            //1. 新增支付流水 ,修改订单状态，改为 支付成功，已付款;
            Flow flow = new Flow ();
            flow.setFlowNum (trade_no);
            flow.setMyorderId (out_trade_no);
            flow.setPayAmount (Float.valueOf (total_amount));
            flow.setPayTime (new Date ());
            Integer carId = orderService.getById (Integer.valueOf (out_trade_no)).getCarId ();
            System.out.println ("==============流水信息============"+flow);
            flowService.save (flow);

            Integer myorderId = Integer.valueOf(out_trade_no);
            couponService.updateById(orderService.getById(myorderId).getCouponNo());


            Car car = carService.getById (carId);
            mav.addObject("out_trade_no", out_trade_no);
            mav.addObject("trade_no", trade_no);
            mav.addObject("total_amount", total_amount);
            mav.addObject("productName", car.getCarName ());
            mav.addObject("pay_time", flow.getPayTime ());
        }else {
            System.out.println("支付出错了，验证签名失败");
        }
        mav.setViewName("order/flow_detail");  // 流水详情中

        return mav;
        }
    // 调用支付 是异步请求， 该方法就是 异步处理的
    @GetMapping("/alipayNotifyNotice")
    public String notifyNotice(){
        return null;
    }

    @RabbitListener(queues = "deadQueue",ackMode = "MANUAL")
    public void onMessage(Message message, Channel channel) throws IOException {
//        System.out.println ("消息进入死信队列");
        String msgBody =new String (message.getBody ());
        Integer orderId =  Integer.valueOf (msgBody);
        System.out.println ("订单编号"+orderId);
        Myorder myorder =orderService.getById (orderId);
        if (myorder!=null && myorder.getMyorderStatus ()==0){
            System.out.println ("死信队列消费成功,未支付");
            myorder.setMyorderStatus (2);
            int rows = orderService.updateOrderStatus (myorder);
            System.out.println ("修改订单状态为2"+rows);
        }
        channel.basicAck (message.getMessageProperties ().getDeliveryTag (),false);
    }
}
